from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.response import Response
from celery_tasks.sms.tasks import send_msm_code
from meiduo_mall.libs.yuntongxun.sms import CCP
# Create your views here.

from random import  randint
from rest_framework.views import APIView

class SMSCodeView(APIView):
    def get(self,request,mobile):
        conn = get_redis_connection('verify')
        #频繁请求验证
        flag=conn.get('sms_%s'%mobile)
        if flag:
            return Response({'message':'请求过于频繁'},400)

        #生成验证码
        sms_code = '%06d'%randint(0,999999)
        print(sms_code)
        #保存redis
        pl = conn.pipeline()#创建管道对象

        pl.setex('sms_%s'%mobile,300,sms_code)
        pl.setex('sms_flag_%s'%mobile,60,1)
        pl.execute() #关闭管道
        #调用发送短信 异步
        send_msm_code.delay(mobile,sms_code)
        #返回结果
        return Response({'message':'ok'},200)